package com.deer.wms.intercept.security;

import com.deer.wms.project.root.util.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : wei
 * @since : 2021-07-29 09:18:23
 **/
public class TokenLogoutHandler implements LogoutHandler {
    private JwtUtil jwtUtil;
    private RedisUtil redisUtil;

    public TokenLogoutHandler(JwtUtil jwtUtil, RedisUtil redisUtil) {
        this.jwtUtil = jwtUtil;
        this.redisUtil = redisUtil;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //从header中获取token
        String token = request.getHeader("token");
        //token不为空，移除token，从redis删除
        if (!StringUtils.isEmpty(token)){
            String username = jwtUtil.getUsername(token);
            redisUtil.remove(username);
        }
    }
}
